package extreme.refactor.gilded_rose;

class GildedRose {
    public static final String AGED_BRIE = "Aged Brie";
    public static final String SULFURAS_HAND_OF_RAGNAROS = "Sulfuras, Hand of Ragnaros";
    public static final String BACKSTAGE_PASSES = "Backstage passes to a TAFKAL80ETC concert";
    public static final int PRICE_CEILING = 50;
    public static final int QUALITY_FLOOR = 0;
    public static final int DATE_OF_SHELF_LIFE = 0;

    CommodityProperty[] commodityProperties;

    public GildedRose(CommodityProperty[] commodityProperties) {
        this.commodityProperties = commodityProperties;
    }

    public void update_quality() {
        for (CommodityProperty commodityProperty : commodityProperties) {
            String name = commodityProperty.name;
            if (!AGED_BRIE.equals(name) && !BACKSTAGE_PASSES.equals(name)) {
                qualityDecrease(commodityProperty, name);
            } else {
                qualityIncrease(commodityProperty, name);
            }
            if (!SULFURAS_HAND_OF_RAGNAROS.equals(name)) {
                commodityProperty.sell_in--;
            }
            if (commodityProperty.sell_in < DATE_OF_SHELF_LIFE) {
                outOfDateGoodsUpdateInfo(commodityProperty, name);
            }
        }
    }

    private void outOfDateGoodsUpdateInfo(CommodityProperty commodityProperty, String name) {
        if (!AGED_BRIE.equals(name)) {
            qualityDecrease(commodityProperty, name);
            outOfDateBackstagePassesUpdateRule(commodityProperty, name);
        } else if (isNotPriceCeiling(commodityProperty.quality)) {
            commodityProperty.quality++;
        }
    }

    private void qualityIncrease(CommodityProperty commodityProperty, String name) {
        if (isNotPriceCeiling(commodityProperty.quality)) {
            commodityProperty.quality++;
            backstagePassesUpdate(commodityProperty, name);
        }
    }

    private void outOfDateBackstagePassesUpdateRule(CommodityProperty commodityProperty, String name) {
        if (BACKSTAGE_PASSES.equals(name)) {
            commodityProperty.quality = QUALITY_FLOOR;
        }
    }

    private void backstagePassesUpdate(CommodityProperty commodityProperty, String name) {
        if (BACKSTAGE_PASSES.equals(name)) {
            if (commodityProperty.sell_in < 11 && isNotPriceCeiling(commodityProperty.quality)) {
                commodityProperty.quality++;
            }
            if (commodityProperty.sell_in < 6 && isNotPriceCeiling(commodityProperty.quality)) {
                commodityProperty.quality++;
            }
        }
    }

    private void qualityDecrease(CommodityProperty commodityProperty, String name) {
        if (commodityProperty.quality > QUALITY_FLOOR && !SULFURAS_HAND_OF_RAGNAROS.equals(name)) {
            commodityProperty.quality--;
        }
    }

    private boolean isNotPriceCeiling(int quality) {
        return quality < PRICE_CEILING;
    }

}
